package cn.ydt.ydt.sso.webapi.service.impl;

import cn.ydt.ydt.common.exception.YdtServiceException;
import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.pojo.user.dto.UserLoginDTO;
import cn.ydt.ydt.pojo.user.model.User;
import cn.ydt.ydt.sso.service.UserService;
import cn.ydt.ydt.sso.webapi.mapper.user.UserMapper;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Value("${ydt.jwt.secret-key}")
    private String secretKey;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    UserMapper userMapper;


    @Override
    public String userLogin(UserLoginDTO userLoginDTO) {
        log.info("判断传过来的数据是否为空");
        if (userLoginDTO == null){
            log.warn("传递过来的参数为空,抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"传递的数据为空");
        }
        log.info("登录信息。。。。。。{}",userLoginDTO.toString());
        log.info("利用authenticationManager进行登录认证");
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUserPhone(),userLoginDTO.getUserPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);

        log.info("登录认证成功！");
        log.info("获取登录用户电话");
        String userPhone = userLoginDTO.getUserPhone();
        log.info("根据userPhone查询用户的信息用于生成jwt");
        User loginUser = userMapper.getUserAllByUserphone(userPhone);
        log.info("保存信息到claims中");
        Map<String,Object> clamis = new HashMap<>();
        clamis.put("userPhone",userPhone);
        clamis.put("userPassword",loginUser.getUserPassword());
        clamis.put("userId",loginUser.getUserId());
        clamis.put("communityId",loginUser.getCommunityId());
        log.info("communityId=={}",loginUser.getCommunityId());
        //用于辨别登录对象
        clamis.put("identity",(byte)1);
        log.info("向jwt中写入数据，生成jwt");
        String jwt = Jwts.builder()
                // Header：指定算法与当前数据类型
                // 格式为： { "alg": 算法, "typ": "jwt" }
                .setHeaderParam(Header.CONTENT_TYPE,"HS256")
                .setHeaderParam(Header.TYPE,Header.JWT_TYPE)
                  // Payload：通常包含Claims（自定义数据）和过期时间
                .setClaims(clamis)
                .setExpiration(new Date(System.currentTimeMillis()+10*24*60*60*1000))
                // Signature：由算法和密钥（secret key）这2部分组成
                .signWith(SignatureAlgorithm.HS256, secretKey)
                // 打包生成
                .compact();
        log.info("jwt生成完成，返回jwt数据");
        return jwt;
    }

}
